package cn.karent.core;

import cn.karent.common.ValidationUtils;
import cn.karent.processor.Processor;
import io.micrometer.tracing.annotation.NewSpan;
import io.micrometer.tracing.annotation.SpanAspect;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.aop.aspectj.annotation.AspectJProxyFactory;
import org.springframework.context.ApplicationContext;
import java.util.List;

/**
 * RocketMQ消费者
 *
 * @author wanshengdao
 * @date 2025/3/20
 */
@Getter
@Setter
@Slf4j
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Consumer {

    @NotBlank(message = "endpoints不能为空")
    private String endpoints;

    @NotBlank(message = "group不能为空")
    private String group;

    @NotBlank(message = "topic不能为空")
    private String topic;

    @NotNull(message = "applicationContext对象不能为空")
    private ApplicationContext applicationContext;

    private DefaultMQPushConsumer consumer;

    private Processor processor;

    public void listen() throws MQClientException {
        ValidationUtils.valid(this);
        log.info("开始监听[{}], group为: {}", topic, group);
        consumer = new DefaultMQPushConsumer(this.group);
        consumer.setNamesrvAddr(this.endpoints);
        consumer.subscribe(this.topic, "*");
        if (processor == null) {
            processor = msg -> log.info("消息: {}", msg);
        }
        consumer.registerMessageListener(getProxyListener());
        consumer.start();
    }

    private Listener getProxyListener() {
        Listener listener = new Listener(processor);
        AspectJProxyFactory proxyFactory = new AspectJProxyFactory(listener);
        SpanAspect aspect = applicationContext.getBean(SpanAspect.class);
        proxyFactory.addAspect(aspect);
        proxyFactory.setProxyTargetClass(true);
        return proxyFactory.getProxy();
    }

    public void shutdown() {
        log.info("开始停止监听topic: {}", topic);
        if (this.consumer == null) {
            log.info("consumer is null");
            return;
        }
        consumer.shutdown();
    }

    @RequiredArgsConstructor
    public static class Listener implements MessageListenerConcurrently {

        private final Processor processor;

        @NewSpan
        @Override
        public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
            for (MessageExt msg : msgs) {
                try {
                    handle(msg);
                } catch (Exception e) {
                    log.warn("消费出现异常, 稍后重试: ", e);
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
            }
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }

        private void handle(MessageExt msg) {
            byte[] body = msg.getBody();
            String s = new String(body);
            log.info("第[{}]次消费, msgId: {}, 内容: {}", msg.getReconsumeTimes(), msg.getMsgId(), s);
            long start = System.currentTimeMillis();
            try {
                processor.process(s);
            } finally {
                log.info("消费耗时: {}ms", System.currentTimeMillis() - start);
            }
        }
    }

}
